package org.opens.util;

import cn.hutool.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 功能描述
 *
 * @author by zhangyuming
 * @date 2022/10/28
 */
public class RestTemplateUtil {

    private static RestTemplate restTemplate = new RestTemplate();

    public static <T> T postOfRequestParam(String url, Map<String, Object> param, Class<T> clazz) {
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        if (param != null) {
            Iterator<Map.Entry<String, Object>> iterator = param.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entity = iterator.next();
                params.add(entity.getKey(), entity.getValue());
            }
        }

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(params, header);

        return restTemplate.postForObject(url, httpEntity, clazz);
    }

    public static <T> T postOfRequestBody(String url, Map<String, Object> param, Class<T> clazz) {
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(param, header);

        return restTemplate.postForObject(url, httpEntity, clazz);
    }

    public static void main(String[] args) {
        Map<String, Object> p1 = new HashMap<>();
        p1.put("id", 1);

        System.out.println(postOfRequestBody("http://localhost:30000/simpleApi/doRequestBody", p1, JSONObject.class));
        System.out.println(postOfRequestParam("http://localhost:30000/simpleApi/doRequestObj", p1, JSONObject.class));
        System.out.println(postOfRequestParam("http://localhost:30000/simpleApi/doRequestParam", p1, JSONObject.class));
    }

}
